package com.intelligentmeterreadingsys.waterlist.copywater.activity;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import com.intelligentmeterreadingsys.R;
import com.intelligentmeterreadingsys.httpserver.RequestUrl;
import com.intelligentmeterreadingsys.httpserver.UploadHttpClient;
import com.intelligentmeterreadingsys.povo.ResourcesPoVo;
import com.intelligentmeterreadingsys.povo.UserWaterVO;
import com.intelligentmeterreadingsys.povo.WaterInfoVO;
import com.intelligentmeterreadingsys.report.activity.ReportNoRFIDActivity;
import com.intelligentmeterreadingsys.util.SharedPreferenceUtil;
import com.intelligentmeterreadingsys.waterlist.copywater.db.CopyWaterDao;

import dbhelper.XmlNameHelper;


import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.GestureDetector;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.GestureDetector.OnGestureListener;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

/**
 * RFID异常抄表
 * @author king
 *
 */
public class CopyWaterNoRFIDActivity extends Activity implements OnClickListener{
	public static final int REQUEST_CODE_TAKE_IMAGE=1;//回调函数标志
	  public RelativeLayout layout=null;
	  public Button button4;//拍照
	  public Button button5;//保存
	  public Button button6;//上传
	  public EditText edit2;//本次刻度
	  public EditText edit3;//备注
	  public TextView textview1;//水表编号
	  public TextView textview2;//水表地址
	  public TextView textview3;//用水量
	  public TextView textview4;//上次抄表刻度
	  public TextView textview5;//用水性质
	  public TextView textview6;//口径
	  public TextView textview7;//用户姓名
	  public TextView textview8;//电话
	  public String waterid;
	  public boolean isupload=false;
	  public static final int ITEM0=Menu.FIRST;//系统值 
	  
	  public List<UserWaterVO> list=null;
	  
	  public boolean isSave=false;
	  public int i=0;
	 
	  public ProgressDialog pd;
	  public SharedPreferenceUtil sh=null;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.copywater_norfid);
		sh=new SharedPreferenceUtil(this);
		init();
	}

	/**
	 * 初始化控件
	 */
	public void init(){		
		button4=(Button)findViewById(R.id.copywater_norfid_paizhao);
		button5=(Button)findViewById(R.id.copywater_norfid_save);
		button6=(Button)findViewById(R.id.copywater_norfid_upload);
		button4.setOnClickListener(this);
		button5.setOnClickListener(this);
		button6.setOnClickListener(this);
		edit2=(EditText)findViewById(R.id.copywater_norfid_thismonthwater);
		edit2.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				
				
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			
				
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				if(list!=null&&list.size()>0){
					if(list.get(i)!=null&&!TextUtils.isEmpty(s.toString())){
						Double thisusewater=Double.parseDouble(s.toString())-list.get(i).getLastmonthwater();
						System.out.println(thisusewater+"用水量");
						textview3.setText(thisusewater+"");
						if(thisusewater>list.get(i).getLowalarmlimit()||thisusewater<list.get(i).getAlarmlimit()){
							textview3.setTextColor(Color.RED);
						}else{
							textview3.setTextColor(Color.BLACK);
						}
					}
				}
				
			}
		});
		
		edit3=(EditText)findViewById(R.id.copywater_norfid_desc);
		textview1=(TextView)findViewById(R.id.copywater_norfid_waternumber);
		textview2=(TextView)findViewById(R.id.copywater_norfid_wateradds);
		textview3=(TextView)findViewById(R.id.copywater_norfid_usewater);	
		textview4=(TextView)findViewById(R.id.copywater_norfid_lastmonthwater);
		textview5=(TextView)findViewById(R.id.copywater_norfid_waterproperties);
		textview6=(TextView)findViewById(R.id.copywater_norfid_metercaliber);
		textview7=(TextView)findViewById(R.id.copywater_norfid_username);
		textview8=(TextView)findViewById(R.id.copywater_norfid_phone);
		layout=(RelativeLayout)findViewById(R.id.copywater_norfid_relativelayout);
		
	    waterid=getIntent().getStringExtra("waterid");
	    if(!TextUtils.isEmpty(waterid)){
	    	CopyWaterDao dao=new CopyWaterDao(this);
	    	this.list=dao.queryUserWaterInfo(null, null, waterid);
	    	dao.close();
			viewDate();
	    }
		
	}

	/**
	 * 展现数据
	 */
	public void viewDate(){
		textview1.setText("");
		textview2.setText("");
		textview3.setText("");
		textview4.setText("");
		textview5.setText("");
		textview6.setText("");
		textview7.setText("");
		textview8.setText("");
		edit2.setText("");
		edit3.setText("");
		if(list!=null&&list.size()>0){
			UserWaterVO water=list.get(0);
			textview1.setText(list.get(i).getWaternumber());
			textview2.setText(list.get(i).getAdds());
			textview4.setText(list.get(i).getLastmonthwater()+"");
			textview5.setText(water.getWaterproperties());
			textview6.setText(water.getMetercaliber());
			textview7.setText(water.getName());
			textview8.setText(water.getPhone());
			edit3.setText(list.get(i).getDesc());
			if(list.get(i).getThismonthwater()>0){
				edit2.setText(list.get(i).getThismonthwater()+"");
				textview3.setText(""+(list.get(i).getThismonthwater()-list.get(i).getLastmonthwater()));
			}
		}
	}
	
	/**
	 * 翻页
	 */
	public void filp(){
		if(i<0){
			i=0;
			Toast.makeText(CopyWaterNoRFIDActivity.this, "没有前面的数据了！", Toast.LENGTH_LONG).show();
		}else if(i>(list.size()-1)){
			i=list.size()-1;
			Toast.makeText(CopyWaterNoRFIDActivity.this, "没有后面的数据了！", Toast.LENGTH_LONG).show();
		}else{
			viewDate();
		}
	}
	@Override
	public void onClick(View v) {
		if(v.getId()==button4.getId()){
			System.out.println("拍照");
			Intent intent=new Intent(CopyWaterNoRFIDActivity.this, ImageSwitcherActivity.class);
			
			Bundle bundle=new Bundle();
			if(list==null||list.size()<1){
				Toast.makeText(CopyWaterNoRFIDActivity.this, "没有水表不能拍照", 1000).show();
				return;
			}
			bundle.putString("otherid", list.get(i).getWaterid());
			bundle.putString("status", "2");
			bundle.putString("classname", "CopyWaterNoRFIDActivity");
			intent.putExtras(bundle);
			startActivity(intent);
			
			
		}else if(button5.getId()==v.getId()){
			if(list==null||list.size()<1){
				Toast.makeText(CopyWaterNoRFIDActivity.this, "没有水表不能保存！", 1000).show();
				return;
			}
			if(TextUtils.isEmpty(edit2.getEditableText().toString())){
				Toast.makeText(CopyWaterNoRFIDActivity.this, "你还没有抄表呢！", 1000).show();
				return;
			}
			if(isupload||list.get(0).getIsupload().equals("1")){
				Toast.makeText(CopyWaterNoRFIDActivity.this, "已经上传过了，不能修改", 1000).show();
				return;
			}
			boolean b=save();
			if(b){
				Toast.makeText(CopyWaterNoRFIDActivity.this, "抄表成功!", 1000).show();
				isSave=true;
			}else{
				Toast.makeText(CopyWaterNoRFIDActivity.this, "保存失败!", 1000).show();
				isSave=false;
			}
			
		}else if(button6.getId()==v.getId()){
			if(isupload){
				Toast.makeText(CopyWaterNoRFIDActivity.this, "已经上传过了", 1000).show();
				return;
			}
			if(!isSave){
				Toast.makeText(CopyWaterNoRFIDActivity.this, "请保存后再上传！", 1000).show();
				return;
			}
			if(list.get(i).getIsupload().equals("1")){
				Toast.makeText(CopyWaterNoRFIDActivity.this, "已经上传过了", 1000).show();
				return;
			}
			pd=new ProgressDialog(CopyWaterNoRFIDActivity.this);
			pd.setMessage("上传中......");
			pd.show();
			CopyWaterDao dao=new CopyWaterDao(CopyWaterNoRFIDActivity.this);
			
			final WaterInfoVO water=dao.queryOneNoUpload(null, list.get(i).getWaterid(), "0");
			dao.close();
			new Thread(){


				@Override
				public void run() {
					
					Map<String, String> map=new HashMap<String, String>();
					
					Map<File, String> mapfile=new HashMap<File, String>();
					Map<String, String> map1=new HashMap<String, String>();
					map1.put("waternumber", water.getWaternumber());
		            map1.put("usewater", water.getThismonthwater()-water.getLastmonthwater()+"");
					map1.put("imsi", sh.getValue(XmlNameHelper.IMSI));
					map1.put("thismonthwater", water.getThismonthwater()+"");
					map1.put("thisdate", water.getThisdate());
					map1.put("desc", water.getDesc());
					map1.put("sid", "0");
					map1.put("isnorfid", water.getIsNorfid());
					List<String> list=water.getImagepath();
					for(int k=0;k<list.size();k++){
						File file=new File(list.get(k));
						if(file.exists()){
							mapfile.put(file, "imagepath");
							map.put(file.getName(), "imagename");
						}
					}
					RequestUrl re=new RequestUrl(CopyWaterNoRFIDActivity.this);
				String respon=	UploadHttpClient.uploadSubmit(re.getUrl(RequestUrl.COPYWATERLIST), map, mapfile,map1);
				if(respon.equals("error")){
					Message msg=myHandler.obtainMessage();
					msg.what=1;
					myHandler.sendMessage(msg);
				}else{
					try {
						JSONObject json=new JSONObject(respon);
						String message=json.getString("message");
						if(message.equals("yes")){
							Message msg=myHandler.obtainMessage();
							msg.what=2;
							myHandler.sendMessage(msg);
						}else{
							Message msg=myHandler.obtainMessage();
							msg.what=3;
							myHandler.sendMessage(msg);
						}
					} catch (JSONException e) {
					       
						Message msg=myHandler.obtainMessage();
						msg.what=3;
						myHandler.sendMessage(msg);
					}
					
				}
					
				}
				
			
			}.start();
		}
	}
	
	/**
	 * 保存抄表数据
	 * @return
	 */
	public boolean save(){
		boolean b=false;
	if(list.get(0).getIsupload().equals("1")){
		Toast.makeText(CopyWaterNoRFIDActivity.this, "已经上传过了不能再抄", 1000).show();
		return false;
	}
	  CopyWaterDao dao=new CopyWaterDao(this);
	  b= dao.isPhotograph(list.get(0).getWaterid());
	  dao.close();
	  if(textview3.getCurrentTextColor()==Color.RED&&b==false){
		 
		  Toast.makeText(CopyWaterNoRFIDActivity.this, "报警了须拍照", 1000).show();
		
		  return false;
	  }
	  CopyWaterDao daos=new CopyWaterDao(this);
	  b= daos.saveWater(list.get(i).getWaterid(), Double.parseDouble(edit2.getEditableText().toString()),
			  edit3.getEditableText().toString(),"1");
		this.list=daos.queryUserWaterInfo(null, null,list.get(0).getWaterid());
		daos.close();
		viewDate();
		return b;
		
	}
	
	
	
	/**
	 * 上传消息处理
	 */
	Handler myHandler=new Handler(){

		@Override
		public void handleMessage(Message msg) {
			
			if(msg.what==2){
				pd.dismiss();
				Toast.makeText(CopyWaterNoRFIDActivity.this, "上传成功", 1000).show();
				CopyWaterDao dao=new CopyWaterDao(CopyWaterNoRFIDActivity.this);
				dao.uploadstatus(list.get(i).getWaterid());
				dao.queryUserWaterInfo(null, null, waterid);
				dao.close();
				isupload=true;
				
			}else{
				pd.dismiss();
				Toast.makeText(CopyWaterNoRFIDActivity.this, "上传失败", 1000).show();
				isupload=false;
			}
			super.handleMessage(msg);
		}
		
	};
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {				
		menu.add(0,ITEM0,0,"RFID异常报案");
		menu.add(0,ITEM0+1,0,"发短息");
		menu.add(0,ITEM0+2,0,"打电话");
		menu.findItem(ITEM0+1);
		
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		
		if(list==null&&list.size()<1){
			Toast.makeText(CopyWaterNoRFIDActivity.this, "没有水表不能进行此操作", 1000).show();
			return false;
		}
		switch (item.getItemId()) {
		case ITEM0:
			  if(list!=null&&list.size()>0){
				  Intent intent=new Intent(CopyWaterNoRFIDActivity.this, ReportNoRFIDActivity.class);
				  intent.putExtra("waterid", list.get(0).getWaterid());
				  startActivity(intent);
			  }
			 
			break;
		case ITEM0+1:
			if(list!=null&&list.size()>0){
				
				Uri smsToUri = Uri.parse("smsto:"); 
				 String userwater=textview3.getText().toString();
			     Intent sendIntent = new Intent(Intent.ACTION_VIEW, smsToUri); 
			      sendIntent.putExtra("address", list.get(0).getPhone());   //电话号码，这行去掉的话，默认就没有电话
			     sendIntent.putExtra("sms_body","尊敬的"+list.get(0).getName()+"用户:你本月用水量为:"+userwater); 
			     sendIntent.setType("vnd.android-dir/mms-sms"); 
			     startActivity(sendIntent);
			}			
			break;
		case ITEM0+2:
			Intent intent = new Intent();
		   intent.setAction("Android.intent.action.CALL");
		   intent.setData(Uri.parse("tel:"+ list.get(0).getPhone()));//mobile为你要拨打的电话号码，模拟器中为模拟器编号也可
		   startActivity(intent);
			break;
		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}
	
	
}
